<template>
  <view class="container">
    <!-- 用户信息栏 -->
    <view class="user-bar">
      <view class="user-info">
        <text class="username">{{ user.titlename || user.tel }}</text>
        <text class="car-number">{{ user.car }}</text>
      </view>
      <uni-icons type="person" size="24" @click="navigateToUserCenter"></uni-icons>
    </view>
    
    <!-- 搜索框 -->
    <view class="search-box">
      <view class="search-container">
        <input 
          class="search-input" 
          placeholder="搜索歌曲" 
          v-model="searchKeyword" 
          @confirm="handleSearch"
        />
        <button class="search-button" @click="handleSearch">搜索</button>
      </view>
    </view>
    <!-- 歌单筛选 -->
    <view class="playlist-filter">
      <picker @change="changePlaylist" :value="playlistIndex" :range="playlists"  range-key="">
        <view class="filter-btn">
          <text>{{ currentPlaylist || '全部歌单' }}</text>
          <uni-icons type="arrowdown" size="14"></uni-icons>
        </view>
      </picker>
    </view>
    <view class="search-status" v-if="searchKeyword">
      <text>搜索结果: "{{ searchKeyword }}" ({{ songs.length }}首)</text>
      <uni-icons type="close" size="16" @click="clearSearch"></uni-icons>
    </view>
    <!-- 歌曲列表 -->
    <scroll-view 
      class="song-list" 
      scroll-y 
      @scrolltolower="loadMore"
      :scroll-with-animation="true"
      :enable-back-to-top="true"
      :style="{ height: scrollHeight + 'px' }"
    >
      <song-item 
        v-for="song in songs" 
        :key="song.id" 
        :song="song"
        :current-playing="currentSong && currentSong.id === song.id && isPlaying"
        @play="playSong"
        @action="handleSongAction"
      />
      
      <!-- 加载更多提示 -->
      <view class="load-more" v-if="loading">
        <uni-load-more status="loading"></uni-load-more>
      </view>
      <view class="load-more" v-else-if="!hasMore && songs.length > 0">
        <text>没有更多了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-tip" v-if="!loading && songs.length === 0">
        <image src="/static/empty.png" mode="aspectFit"></image>
        <text>暂无歌曲，点击下方按钮添加</text>
      </view>
    </scroll-view>
    
    <!-- 添加按钮 -->
    <view class="add-btn" @click="navigateToAddSong">
      <uni-icons type="plus" size="24" color="#fff"></uni-icons>
    </view>
    
    <!-- 播放器 -->
    <view class="player-bar" v-if="currentSong">
      <image class="cover" :src="currentSong.cover || '/static/logo.png'"></image>
      <view class="song-info">
        <text class="title">{{ currentSong.title }}</text>
        <text class="artist">{{ currentSong.artist || '未知歌手' }}</text>
      </view>
      
      <view class="player-controls">
        <button @tap="showLyrics = !showLyrics" class="control-button">
          {{ showLyrics ? '隐' : '显' }}
        </button>
        <button @tap="playPrev" class="control-button">上</button>
        <button @tap="togglePlay" class="control-button">
          {{ isPlaying ? '暂' : '播' }}
        </button>
        <button @tap="playNext" class="control-button">下</button>
        <button @tap="stopPlay" class="control-button">停</button>
      </view>
    </view>
    
    <view class="lyrics-panel" v-if="showLyrics" @click="showLyrics = false">
      <view v-if="lyrics.length === 0" class="no-lyrics">
        <image src="/static/music-note.png" mode="aspectFit"></image>
        <text>暂无歌词</text>
      </view>
      <scroll-view v-else class="lyrics-container" scroll-y :style="{ height: lyricsHeight + 'px' }" ref="lyricsContainer">
        <view 
          v-for="(line, index) in lyrics" 
          :key="index" 
          :ref="'lyric-' + index"
          class="lyric-line" 
          :class="{ 'active': currentLyricIndex === index }"
        >
          {{ line.text }}
        </view>
      </scroll-view>
    </view>
    
    <!-- 锁屏控制组件 -->
    <lock-screen-controls 
      ref="lockScreen"
      :visible="showLockScreenControls"
      :current-song="currentSong"
      :is-playing="isPlaying"
      :current-time="currentTime"
      :duration="duration"
      @toggle-play="togglePlay"
      @play-prev="playPrev"
      @play-next="playNext"
      @seek="handleSeek"
    />
  </view>
</template>

<script>
import api from '@/store/musics_api.js';
import SongItem from '@/pages/musics/song-item.vue';
import LockScreenControls from '@/pages/musics/lock-screen-controls.vue';

export default {
  components: {
    LockScreenControls,
    SongItem
  },
  data() {
    return {
      user: {},
      songs: [],
      playlists: ['全部歌单'],
      currentPlaylist: '',
      playlistIndex: 0,
      searchKeyword: '',
      currentPage: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      hasMore: true,
      scrollHeight: 0,
      currentSong: null,
      isPlaying: false,
      audioContext: null,
      currentSongIndex: -1,
      playHistory: [],
      lyrics: [],
      currentLyricIndex: -1,
      showLyrics: false,
      showLockScreenControls: false,
      currentTime: 0,
      duration: 0,
      lockScreenEnabled: false,
      isLocked: false,
    }
  },
  onReady() {
    this.calculateScrollHeight();
    const systemInfo = uni.getSystemInfoSync();
    this.lyricsHeight = systemInfo.windowHeight - 120;
  },
  onLoad() {
    this.user = uni.getStorageSync('user');
    if (!this.user) {
      uni.redirectTo({
        url: '/pages/user/login'
      });
      return;
    }
    
    this.loadSongs();
    this.fallbackLockScreenDetection();
  },
  onShow() {
    if (this.user) {
      this.refreshData();
    }
    if (this.audioContext) {
      this.audioContext.sessionCategory = 'playback';
    }
  },
  onUnload() {
    this.destroyAudio();
  },
  onHide() {
    if (this.audioContext && this.isPlaying) {
      this.audioContext.sessionCategory = 'soloAmbient';
    }
  },
  
  methods: {
    initLockScreenSupport() {
      console.log('初始化纯前端锁屏支持');
      
      if (typeof document !== 'undefined') {
        document.addEventListener('visibilitychange', () => {
          this.showLockScreenControls = document.hidden;
          console.log('页面可见性变化:', document.hidden ? '锁屏' : '解锁');
        });
      }
      
      uni.onAppHide(() => {
        this.showLockScreenControls = true;
        console.log('App进入后台');
      });
      
      uni.onAppShow(() => {
        this.showLockScreenControls = false;
        console.log('App回到前台');
      });
    },
    
    fallbackLockScreenDetection() {
      this.lockScreenEnabled = true;
      
      if (typeof document !== 'undefined') {
        document.addEventListener('visibilitychange', () => {
          if (document.hidden) {
            this.showLockScreenControls = true;
            console.log('页面隐藏，显示锁屏控制');
          } else {
            this.showLockScreenControls = false;
            console.log('页面显示，隐藏锁屏控制');
          }
        });
      }
      
      uni.onWindowResize((res) => {
        if (res.size.windowWidth === 0 && res.size.windowHeight === 0) {
          this.showLockScreenControls = true;
        }
      });
    },
    
    parseLyrics(lyricText) {
      if (!lyricText) return [];
      
      const lines = lyricText.split('\n');
      const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/;
      const lyrics = [];
      
      lines.forEach(line => {
        const matches = timeRegex.exec(line);
        if (matches) {
          const minutes = parseInt(matches[1]);
          const seconds = parseInt(matches[2]);
          const milliseconds = parseInt(matches[3].length === 3 ? matches[3] : matches[3] * 10);
          const time = minutes * 60 + seconds + milliseconds / 1000;
          
          const text = line.replace(timeRegex, '').trim();
          if (text) {
            lyrics.push({ time, text });
          }
        }
      });
      
      return lyrics;
    },
    
    updateLyrics(currentTime) {
      if (!this.lyrics.length) return;
      
      for (let i = this.lyrics.length - 1; i >= 0; i--) {
        if (currentTime >= this.lyrics[i].time) {
          if (this.currentLyricIndex !== i) {
            this.currentLyricIndex = i;
            this.$nextTick(() => {
              const lyricsContainer = this.$refs.lyricsContainer;
              if (lyricsContainer) {
                const currentLine = this.$refs[`lyric-${i}`]?.[0];
                if (currentLine) {
                  const targetPosition = currentLine.$el.offsetTop - (lyricsContainer.$el.offsetHeight * 1 / 3);
                  lyricsContainer.scrollTop = targetPosition;
                }
              }
            });
          }
          break;
        }
      }
    },
    
    calculateScrollHeight() {
      this.$nextTick(() => {
        const systemInfo = uni.getSystemInfoSync();
        const query = uni.createSelectorQuery().in(this);
        
        query.select('.user-bar').boundingClientRect();
        query.select('.search-box').boundingClientRect();
        query.select('.playlist-filter').boundingClientRect();
        query.select('.player-bar').boundingClientRect();
        
        query.exec(res => {
          const userBarHeight = res[0]?.height || 0;
          const searchBoxHeight = res[1]?.height || 0;
          const playlistFilterHeight = res[2]?.height || 0;
          const playerBarHeight = res[3]?.height || 0;
          
          this.scrollHeight = systemInfo.windowHeight - userBarHeight - searchBoxHeight - playlistFilterHeight - playerBarHeight;
        });
      });
    },
    
    async loadSongs() {
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        const [error, res] = await api.getSongs(
          this.user.id,
          this.currentPlaylist,
          this.currentPage,
          this.pageSize
        );
    
        if (error) throw error;
    
        const newSongs = res.data?.data || [];
        this.total = res.data?.total || 0;
    
        this.songs = this.currentPage === 1 ? newSongs : [...this.songs, ...newSongs];
        
        if (!this.searchKeyword) {
          const uniquePlaylists = new Set(this.playlists);
          newSongs.forEach(song => {
            if (song.playlist && !uniquePlaylists.has(song.playlist)) {
              uniquePlaylists.add(song.playlist);
            }
          });
          if (!uniquePlaylists.has('全部歌单')) {
            uniquePlaylists.add('全部歌单');
          }
          this.playlists = Array.from(uniquePlaylists);
        }
        
        this.hasMore = this.songs.length < this.total;
        
      } catch (error) {
        console.error('加载失败:', error);
      } finally {
        this.loading = false;
      }
    },
    
    refreshData() {
      this.currentPage = 1;
      this.hasMore = true;
      this.loadSongs();
    },
    
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.currentPage++;
        this.loadSongs();
      }
    },
    
    changePlaylist(e) {
      const selectedIndex = e.detail.value;
      this.currentPlaylist = this.playlists[selectedIndex] === '全部歌单' 
        ? '' 
        : this.playlists[selectedIndex];
      this.playlistIndex = selectedIndex;
      
      this.currentPage = 1;
      this.hasMore = true;
      this.loadSongs();
    },
    
    updateLockScreenInfo() {
      this.$refs.lockScreen?.updateState?.({
        isPlaying: this.isPlaying,
        currentTime: this.currentTime
      });
    },
    
    handleSeek(position) {
      if (this.audioContext) {
        this.audioContext.seek(position);
      }
    },
    
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        uni.showToast({
          title: '请输入搜索内容',
          icon: 'none'
        });
        return;
      }
    
      uni.showLoading({
        title: '搜索中...'
      });
    
      api.searchSongs(this.user.id, this.searchKeyword.trim())
        .then(([error, res]) => {
          uni.hideLoading();
          
          if (error) {
            console.error('搜索失败:', error);
            uni.showToast({
              title: '搜索失败',
              icon: 'none'
            });
            return;
          }
    
          if (res.data && Array.isArray(res.data.data)) {
            this.songs = res.data.data;
            this.total = res.data.total || 0;
            this.hasMore = false;
            
            if (this.songs.length === 0) {
              uni.showToast({
                title: '没有找到相关歌曲',
                icon: 'none'
              });
            }
          } else {
            this.songs = [];
            uni.showToast({
              title: '搜索结果格式错误',
              icon: 'none'
            });
          }
        });
    },
    
    clearSearch() {
      this.searchKeyword = '';
      this.refreshData();
    },
    
    initAudio() {
      this.destroyAudio();
      
      this.audioContext = uni.createInnerAudioContext();
      this.audioContext.autoplay = true;
      
      try {
        if (typeof this.audioContext.mixWithOther !== 'undefined') {
          this.audioContext.mixWithOther = true;
        }
      } catch (e) {
        console.warn('设置音频混合模式失败:', e);
      }
      
      this.audioContext.onTimeUpdate(() => {
        this.currentTime = this.audioContext.currentTime;
        this.duration = this.audioContext.duration;
        
        if (this.isLocked) {
          this.updateLockScreenInfo();
        }
        
        this.updateLyrics(this.audioContext.currentTime);
      });
      
      this.audioContext.onPlay(() => {
        this.isPlaying = true;
        this.updateLockScreenInfo();
      });
      
      this.audioContext.onPause(() => {
        this.isPlaying = false;
        this.updateLockScreenInfo();
      });
      
      this.audioContext.onStop(() => {
        this.isPlaying = false;
      });
      
      this.audioContext.onTimeUpdate(() => {
        this.currentTime = this.audioContext.currentTime;
        this.duration = this.audioContext.duration || this.duration;
        this.updateLockScreenInfo();
      });
      
      this.audioContext.onEnded(() => {
        console.log('当前歌曲播放结束');
        this.isPlaying = false;
        if (this.songs.length > 0) {
          this.$nextTick(() => {
            console.log('正在下一首');
            this.playNext();
          });
        }
      });
      
      this.audioContext.onError((res) => {
        console.error('播放错误:', res);
        uni.showToast({ title: '播放失败', icon: 'none' });
        this.isPlaying = false;
      });
    },
    
    destroyAudio() {
      if (this.audioContext) {
        this.audioContext.stop();
        this.audioContext.destroy();
        this.audioContext = null;
      }
    },
    
    playSong(song) {
      if (this.currentSong?.id === song.id) {
        this.togglePlay();
        return;
      }
      
      const index = this.songs.findIndex(s => s.id === song.id);
      if (index === -1) return;
      
      this.currentSongIndex = index;
      this.currentSong = song;
      
      if (!this.audioContext) {
        this.initAudio();
      }
      
      this.audioContext.src = song.url;
      this.audioContext.play();
      this.lyrics = this.parseLyrics(song.lyrics);
      this.currentLyricIndex = -1;
      
      this.audioContext.onTimeUpdate(() => {
        this.updateLyrics(this.audioContext.currentTime);
      });
      
      this.addToPlayHistory(song);
    },
    
    addToPlayHistory(song) {
      this.playHistory = this.playHistory.filter(s => s.id !== song.id);
      this.playHistory.unshift(song);
      if (this.playHistory.length > 50) {
        this.playHistory.pop();
      }
    },
    
    togglePlay() {
      if (!this.audioContext || !this.currentSong) return;
      
      if (this.isPlaying) {
        this.audioContext.pause();
      } else {
        if (!this.audioContext.src) {
          this.audioContext.src = this.currentSong.url;
        }
        this.audioContext.play();
      }
    },
    
    stopPlay() {
      if (this.audioContext) {
        this.audioContext.stop();
        this.isPlaying = false;
      }
    },
    
    playPrev() {
      if (this.songs.length === 0) return;
      
      if (this.playHistory.length > 1) {
        const prevSong = this.playHistory[1];
        this.playSong(prevSong);
        return;
      }
      
      let prevIndex = this.currentSongIndex - 1;
      if (prevIndex < 0) {
        prevIndex = this.songs.length - 1;
      }
      
      this.playSong(this.songs[prevIndex]);
    },
    
    playNext() {
      if (this.songs.length === 0) return;
      
      let nextIndex = this.currentSongIndex + 1;
      if (nextIndex >= this.songs.length) {
        nextIndex = 0;
      }
      
      this.playSong(this.songs[nextIndex]);
    },
    
    handleSongAction(song) {
      uni.showActionSheet({
        itemList: ['编辑', '删除'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.editSong(song);
          } else if (res.tapIndex === 1) {
            this.deleteSong(song.id);
          }
        }
      });
    },
    
    editSong(song) {
      uni.navigateTo({
        url: `/pages/songs/add?id=${song.id}`
      });
    },
    
    async deleteSong(songId) {
      try {
        uni.showModal({
          title: '提示',
          content: '确定要删除这首歌曲吗？',
          success: async (res) => {
            if (res.confirm) {
              uni.showLoading({
                title: '删除中...'
              });
              
              const response = await api.deleteSong(songId, this.user.id);
                        
              if (!Array.isArray(response) || response.length !== 2) {
                throw new Error('API返回格式错误');
              }
            
              const [error, res] = response;
            
              if (error) throw error;
              if (!res.data || res.data.error) throw new Error(res.data?.message || '删除失败');
            
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              if (this.currentSong?.id === songId) {
                this.stopPlay();
                this.currentSong = null;
                this.currentSongIndex = -1;
              }
              
              this.refreshData();
            }
          }
        });
      } catch (error) {
        console.error('删除歌曲失败:', error);
        uni.showToast({
          title: error.message || '删除失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    navigateToAddSong() {
      uni.navigateTo({
        url: '/pages/songs/add'
      });
    },
    
    navigateToUserCenter() {
      uni.navigateTo({
        url: '/pages/user/info'
      });
    }
  }
}
</script>

<style>
.lock-screen-controls {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 40rpx;
}

.no-lyrics {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.no-lyrics image {
  width: 150rpx;
  height: 150rpx;
  opacity: 0.5;
  margin-bottom: 30rpx;
}

.no-lyrics text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 28rpx;
}

.lyrics-panel {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 120rpx;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.lyrics-container {
  width: 80%;
  height: 100%;
  text-align: center;
  color: #f00;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
}

.lyric-line {
  padding: 20rpx 0;
  font-size: 40rpx;
  color: rgba(255, 255, 255, 0.6);
  transition: all 0.3s;
}

.lyric-line.active {
  color: #fff;
  font-size: 48rpx;
  font-weight: bold;
}

.control-button {
  margin: 0 1px;
  background: none;
  border: 1px solid #ddd;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  line-height: 30px;
  color: #00f;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 0; 
}

.container {
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.user-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
}

.car-number {
  font-size: 24rpx;
  color: #666;
  margin-top: 8rpx;
}

.search-box {
  padding: 20rpx 30rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
}

.search-container {
  display: flex;
  width: 100%;
  border: 1px solid #eee;
  border-radius: 50rpx;
  overflow: hidden;
}

.search-input {
  flex: 1;
  padding: 20rpx;
  height: 50rpx;
  font-size: 28rpx;
}

.search-button {
  width: 130rpx;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 0 50rpx 50rpx 0;
  font-size: 30rpx;
}

.playlist-filter {
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.filter-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 200rpx;
  padding: 10rpx 20rpx;
  background-color: #f0f0f0;
  border-radius: 50rpx;
}

.song-list {
  width: 100%;
  -webkit-overflow-scrolling: touch;
}

.load-more {
  padding: 20rpx;
  text-align: center;
  color: #999;
  font-size: 24rpx;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-tip image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-tip text {
  color: #999;
  font-size: 28rpx;
}

.add-btn {
  position: fixed;
  right: 40rpx;
  bottom: 160rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #007aff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
  z-index: 99;
}

.player-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  border-top: 1rpx solid #eee;
  z-index: 100;
}

.player-bar .cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.player-bar .song-info {
  flex: 1;
  overflow: hidden;
  margin-right: 20rpx;
}

.player-bar .title {
  font-size: 28rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

.player-bar .artist {
  font-size: 24rpx;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

.player-bar .player-controls {
  display: flex;
  align-items: center;
  flex-shrink: 0; 
}

.player-bar .play-btn {
  margin: 0 20rpx;
}

.search-status {
  padding: 10rpx 30rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 24rpx;
  color: #666;
}

.control-btn {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 30rpx;
  color: white;
  font-size: 40rpx;
}

.control-btn:active {
  background: rgba(255, 255, 255, 0.4);
}
</style>